package com.iwords.android;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class UserSettings extends Activity {
	private boolean emailValid = false;
	private boolean passwordValid = false;
	private boolean passwordConfirmValid = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);
		try {
			initSettings();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 用户email，填写后，检查是否可用
		final EditText email = (EditText) findViewById(R.id.register_email);
		email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// System.out.println("email.View.OnFocusChangedListener() hasFocus="+hasFocus);
				if (hasFocus)
					return;
				validEmail();
				if (emailValid) {
					email.setTextColor(getResources().getColor(R.color.text_color_green));
					emailValid = true;
				} else {
					emailValid = false;
					email.setTextColor(getResources().getColor(R.color.text_color));// red
					displayMessage("Email不合法或已被占用。");
				}
			}
		});
		// 用户password，填写后，检查是否为空
		EditText password = (EditText) findViewById(R.id.register_password);
		password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// System.out.println("password.View.OnFocusChangedListener() hasFocus="+hasFocus);
				if (hasFocus)
					return;
				validPassword();
			}
		});
		// 用户password_confirm，填写后，检查两次密码是否一致
		EditText password_confirm = (EditText) findViewById(R.id.register_password_confirm);
		password_confirm.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus)
					return;
				validPasswordConfirm();
			}
		});
	}

	private void validPasswordConfirm() {
		EditText password = (EditText) findViewById(R.id.register_password);
		EditText password_confirm = (EditText) findViewById(R.id.register_password_confirm);
		String password_confirmText = password_confirm.getText().toString();
		String passwordText = password.getText().toString();
		if (passwordText != null && passwordText.equals(password_confirmText)) {
			password_confirm.setTextColor(getResources().getColor(R.color.text_color_green));
			passwordConfirmValid = true;
		} else {
			password_confirm.setTextColor(getResources().getColor(R.color.text_color));
			displayMessage("两次输入密码不一致。");
			passwordConfirmValid = false;
		}
	}
	private void vibrate(){
		Vibrator mVibrator = (Vibrator)getApplication().getSystemService(android.app.Service.VIBRATOR_SERVICE);
		mVibrator.vibrate(new long[]{50,50},-1);
	}

	private void validPassword() {
		EditText password = (EditText) findViewById(R.id.register_password);
		String passwordText = password.getText().toString();
		if (passwordText != null && passwordText.trim().length() > 0) {
			password.setTextColor(getResources().getColor(R.color.text_color_green));
			passwordValid = true;
		} else {
			password.setTextColor(getResources().getColor(R.color.text_color));
			displayMessage("密码不能为空，且首尾空格会被忽略。");
			passwordValid = false;
		}
	}

	public void settingsHandler(View view) {
		this.vibrate();
		EditText countdown = (EditText) findViewById(R.id.settings_countdown);
		EditText batch = (EditText) findViewById(R.id.settings_batch_number);

		String paramString = "&countdown=" + countdown.getText().toString() + "&batch_number="
				+ batch.getText().toString();
		saveSettings(paramString);

		this.finish();
	}

	private String getUUID() {
		final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
		final String tmDevice, tmSerial, androidId;
		tmDevice = "" + tm.getDeviceId();
		tmSerial = "" + tm.getSimSerialNumber();
		androidId = ""
				+ android.provider.Settings.Secure.getString(getContentResolver(),
						android.provider.Settings.Secure.ANDROID_ID);
		UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
		String deviceId = deviceUuid.toString();
		//System.out.println("IWords.getUUID() deviceId = " + deviceId);
		return deviceId;
	}

	private void initSettings() throws Exception {
		SharedPreferences preferences = this.getSharedPreferences(IWords.class.getName(), MODE_PRIVATE);
		String username = preferences.getString("username", null);
		if (!getUUID().equals(username)) {
			LinearLayout registerForm = (LinearLayout) this.findViewById(R.id.register_form);
			registerForm.setVisibility(View.GONE);
		}

		JSONObject settings = ((IWordsApp) getApplicationContext()).getUserSettings();
		EditText countdown = (EditText) findViewById(R.id.settings_countdown);
		if (settings.has("countdown")) {
			countdown.setText(settings.getString("countdown"));
		}
		EditText batch = (EditText) findViewById(R.id.settings_batch_number);
		if (settings.has("batch_number")) {
			batch.setText(settings.getString("batch_number"));
		}
	}

	private String paramString() {
		String email = ((EditText) findViewById(R.id.register_email)).getText().toString();
		String password = ((EditText) findViewById(R.id.register_password)).getText().toString();
		// 绑定到请求 Entry
		String paramStr = "&username=" + CodeUtils.encode(email);
		paramStr += "&password=" + CodeUtils.encode(password);
		// 有用户昵称不能为空的限制，先添加一个绕过
		paramStr += "&nickname=nickname";
		return paramStr;
	}

	private void validEmail(){
		//System.out.println("Register.validEmail()");
		//new Exception().printStackTrace();
		if(getIntent().hasExtra("fromConfigMenu")) {
			this.emailValid = true;
			return;//修改时，email只读，无需验证
		}
		EditText emailText = (EditText)findViewById(R.id.register_email);
		String email =emailText.getText().toString();
		if(!isMail(email)) return;
		String href = this.getResources().getString(R.string.user_email_valid);
		href+=email;
		HttpPost request = new HttpPost(href);
		//System.out.println("Register.valid()! href="+href);
		try {
			// 发送请求
			HttpResponse httpResponse = new DefaultHttpClient().execute(request);
			// 得到应答的字符串，这也是 JSON 格式保存的数据	
			
			String retSrc = EntityUtils.toString(httpResponse.getEntity());
			//System.out.println("Register.valid() retSrc="+retSrc);
			retSrc = CodeUtils.decode(retSrc);
			//System.out.println("Register.valid() after decode retSrc="+retSrc);
			// 生成 JSON 对象
			JSONObject jSONObject = new JSONObject(retSrc);
			boolean success = jSONObject.getBoolean("isSuccess");
			if(success){
				emailValid = jSONObject.getBoolean("defaultValue");
			}else{
				emailValid = false;
			}
		}catch(Exception e){
			e.printStackTrace();
			emailValid = false;
		}
	}

	private boolean isMail(String str) {
		String check = "^([a-z0-9A-Z]+[-|\\._]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		Pattern regex = Pattern.compile(check);
		Matcher matcher = regex.matcher(str);
		boolean isMatched = matcher.matches();
		if (isMatched) {
			return true;
		} else {
			return false;
		}
	}

	/** 用户点击注册后，提交注册信息。 */
	public void bindingUser(View view) {
		this.vibrate();
		this.validPassword();
		this.validPasswordConfirm();
		// System.out.println("Register.registerHandler() getIntent().hasExtra(\"fromConfigMenu\") = "+getIntent().hasExtra("fromConfigMenu"));
		if (!getIntent().hasExtra("fromConfigMenu")) {
			this.validEmail();
		}
		if (!this.emailValid) {
			displayMessage("email信息不合规范或已被注册。");
			return;
		}
		if (!this.passwordValid) {
			displayMessage("请填写密码信息。");
			return;
		}
		if (!this.passwordConfirmValid) {
			displayMessage("密码确认信息有误。");
			return;
		}

		String href = this.getResources().getString(R.string.user_update);
		// System.out.println("UserSettings.bindingUser()! href="+href);
		try {
			href = href + paramString() + "&userid=" + ((IWordsApp) getApplicationContext()).getUser().getUserid();
			//System.out.println("UserSettings.bindingUser() ! href=" + href);
			HttpPost request = new HttpPost(href);

			// 发送请求
			HttpResponse httpResponse = new DefaultHttpClient().execute(request);
			// 得到应答的字符串，这也是 JSON 格式保存的数据

			String retSrc = EntityUtils.toString(httpResponse.getEntity());
			//System.out.println("UserSettings.bindingUser() retSrc=" + retSrc);
			retSrc = CodeUtils.decode(retSrc);
			//System.out.println("UserSettings.bindingUser() after decode retSrc=" + retSrc);
			// 生成 JSON 对象
			JSONObject jSONObject = new JSONObject(retSrc);
			boolean success = jSONObject.getBoolean("isSuccess");
			if (success) {
				this.displayMessage("绑定成功。");
				//设置本机信息，下次自动使用所设置的账号登录
				SharedPreferences preferences = this.getSharedPreferences(IWords.class.getName(), MODE_PRIVATE);
				SharedPreferences.Editor editor = preferences.edit();
				EditText emailText = (EditText)findViewById(R.id.register_email);
				String email =emailText.getText().toString();
				EditText passwordText = (EditText)findViewById(R.id.register_password);
				String password =passwordText.getText().toString();
				//System.out.println("UserSettings.bindingUser() autoLogin = "+true);
				//System.out.println("UserSettings.bindingUser() username = "+email);
				//System.out.println("UserSettings.bindingUser() password = "+password);
				editor.putBoolean("autoLogin", true);				
				editor.putString("username", email);
				editor.putString("password", password);
				editor.commit();
				this.finish();
			} else {
				this.displayMessage("绑定失败：" + jSONObject.getString(""));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private boolean saveSettings(String paramString) {
		String href = this.getResources().getString(R.string.user_save_config);
		// System.out.println("**********************UserSettings.saveSettings()! href="+href);
		try {

			href = href + ((IWordsApp) getApplicationContext()).getUser().getUserid() + paramString;
			HttpPost request = new HttpPost(href);
			JSONObject jSONObject = ServerAccessor.access(this, request);

			boolean success = jSONObject.getBoolean("isSuccess");
			if (success) {
				((IWordsApp) getApplicationContext()).loadUserSettings();// 刷新当前缓存在IWordsApp实例中的UserSettings
				displayMessage("保存成功。");
			} else {
				displayMessage(CodeUtils.decode(jSONObject.getString("message")));
			}
			return success;
		} catch (NeedPayException ne) {
			Intent intent = new Intent(this, com.iwords.android.AlipayActivity.class);
			this.startActivity(intent);
		} catch (Exception e) {
			this.displayMessage(e.getMessage());
		}
		return false;
	}

	private void displayMessage(String message) {
		Toast t1 = Toast.makeText(getApplication(), message, Toast.LENGTH_SHORT);
		t1.show();
	}

	public void onResume() {
		super.onResume();
		com.mobclick.android.MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		com.mobclick.android.MobclickAgent.onPause(this);
	}

}
